package bubuntux.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

public abstract class Unix {

	public static List<String> exec(CommandLine command) {
		return resultOf(execute(command));
	}

	public static String execUnique(CommandLine command) {
		String uniqResult = ""; // Alway return something
		List<String> result = exec(command);
		if (result.size() > 0) {
			uniqResult = result.get(0);
		}
		return uniqResult;
	}

	public static int execUniqueInt(CommandLine command) {
		int result = -1;
		String rs = execUnique(command);
		if (StringUtils.isNotBlank(rs) && StringUtils.isAlphanumericSpace(rs)) {
			// Prevent Number Expection
			result = Integer.parseInt(rs);
		}
		return result;
	}

	public static BufferedReader execute(CommandLine command) {
		BufferedReader reader = null;

		if (command != null) { // Prevent Null Pointer Exception

			command.cleanParameters(); // Prevent Index Out Of Bounds Exception

			if (command.isNotEmpty()) { // Prevent Index Out Of Bounds Exception
				try {
					Runtime run = Runtime.getRuntime();
					Process p = run.exec(command.toStringArray());
					InputStreamReader in = new InputStreamReader(
							p.getInputStream());
					reader = new BufferedReader(in);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return reader;
	}

	public static String nextLineOf(BufferedReader reader) {
		String line = null;
		if (reader != null) {
			try {
				line = reader.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return line;
	}

	@SuppressWarnings("unchecked")
	public static List<String> resultOf(BufferedReader reader) {
		List<String> result = new ArrayList<String>();
		if (reader != null) {// Prevent NullPinterException
			try {
				result = IOUtils.readLines(reader);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return result;
	}

	public static List<String> resultOf(BufferedReader reader, int bufferSize) {
		ArrayList<String> result = new ArrayList<String>();
		resultOf(reader, bufferSize, result);
		return result;
	}

	public static void resultOf(BufferedReader reader, int bufferSize,
			ArrayList<String> result) {
		if (reader != null && result != null) {
			result.clear();
			try {
				String line = reader.readLine();
				while (line != null) {
					result.add(line);
					if (result.size() < bufferSize) {
						line = reader.readLine();
					} else {
						break;
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
